package com.eerl.pdev.gen;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ide.CopyPasteManager;
import org.jetbrains.annotations.NotNull;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Objects;

public class CheckStepGen extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        try {
            String checkName = Objects.requireNonNull(CopyPasteManager.getInstance().getContents()).getTransferData(DataFlavor.stringFlavor).toString();

            String checkStepStr
                  = "{funcName}(Role, _) ->\n" +
                    "        Args = #{},\n" +
                    "        StepList = [],\n" +
                    "        {funcName}1(StepList, Role, Args).\n" +
                    "    \n" +
                    "{funcName}1([], Role, Args) -> {ok, Role, Args};\n" +
                    "{funcName}1([Step | T], Role, Args) ->\n" +
                    "    case do_{funcName}(Step, Role, Args) of\n" +
                    "        ok -> {funcName}1(T, Role, Args);\n" +
                    "        {ok, NewRole} -> {funcName}1(T, NewRole, Args);\n" +
                    "        {ok, NewRole, NewArgs} -> {funcName}1(T, NewRole, NewArgs);\n" +
                    "        {false, ErrCode} -> {false, ErrCode};\n" +
                    "        {false, ErrCode, ErrArgs} -> {false, ErrCode, ErrArgs}\n" +
                    "    end.\n" +
                    "\n" +
                    "do_{funcName}(_Step, _Role, _Args) ->\n" +
                    "    ?ERR(\"未知步骤，Step：~w，Args： ~w\", [_Step, _Args]),\n" +
                    "    {false, 0}.";
            checkStepStr = checkStepStr.replaceAll("\\{funcName}", checkName);
            CopyPasteManager.getInstance().setContents(new StringSelection(checkStepStr));
        } catch (UnsupportedFlavorException | IOException ex) {
            throw new RuntimeException(ex);
        }

    }
}
